var ctx = window.daijia.ctx;
var lng = window.daijia.lng;
var lat = window.daijia.lat;
var map = null; //地图对象
var offset = 0;
var limit = 20;
var pagingLimit = 20;//显示分页时的条数
var currentTotalElements = 0;//当前显示总条数
var pageLoading = true;//是否能滚动加载
var hasShowPages = false;//是否已显示分页
var firstLoadPages = true;//分页初始化时 不自动加载
//筛选条件,
var search_orderNumber = null;
var search_clientPhone = null;
var search_driverPhone = null;
var search_companyName = null;
var search_startTime = null;
var search_endTime = null;
var search_treatment = null;
var search_startFinishTime = null;
var search_endFinishTime = null;
var search_orderType = [];
var errand_orderType = [];
var search_status = [];
var orderTypeId;

$(document).ready(function () {

    window.setInterval("window.location.reload(true)", 1000 * 60);

    //添加订单开始
    $("#addOrder").click(function () {
        $('#dialog_order').modal();
    });
    $("#dialog_order").on("shown.bs.modal", function () {
        initialize();
    });
    $("#close_modal").click(function () {
        $('#dialog_order').modal("hide");
    });

    $("#serverTime").change(function () {
        getEmployee();
    });
    $("#limit").click(function () {
        getEmployee();
    });


    //定位

    //自动补全交付地点


    //添加订单结束
    $("#startTime1").datetimepicker({
        format: 'yyyy-mm-dd HH:ii',
        language: 'zh-CN',
        minView: 'hour',
        pickDate: true,
        pickTime: false,
        inputMask: false,
        autoclose: true
    });
    $('#serverTime').change(function () {
        if (!(/^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)\s+([01][0-9]|2[0-3]):[0-5][0-9]$/.test($('#serverTime').val()))) {
            $.scojs_message("请输入正确的时间格式,如:2015-12-30 12:30", $.scojs_message.TYPE_ERROR);
            $('#serverTime').val('');
        }
    });

    $("#startTime").datetimepicker({
        format: "yyyy-mm-dd HH:ii",
        language: 'zh-CN',
        showMeridian: true,
        autoclose: true,
        todayBtn: true
    });
    $("#endTime").datetimepicker({
        format: "yyyy-mm-dd HH:ii",
        language: 'zh-CN',
        showMeridian: true,
        autoclose: true,
        todayBtn: true
    });
    $("#startFinishTime").datetimepicker({
        format: "yyyy-mm-dd HH:ii",
        language: 'zh-CN',
        showMeridian: true,
        autoclose: true,
        todayBtn: true
    });
    $("#endFinishTime").datetimepicker({
        format: "yyyy-mm-dd HH:ii",
        language: 'zh-CN',
        showMeridian: true,
        autoclose: true,
        todayBtn: true
    });

    $("#zj_startTime1").datetimepicker({
        format: 'yyyy-mm-dd HH:ii',
        language: 'zh-CN',
        minView: 'hour',
        pickDate: true,
        pickTime: false,
        inputMask: false,
        autoclose: true
    });
    $('#zj_serverTime').change(function () {
        if (!(/^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)\s+([01][0-9]|2[0-3]):[0-5][0-9]$/.test($('#zj_serverTime').val()))) {
            $.scojs_message("请输入正确的时间格式,如:2015-12-30 12:30", $.scojs_message.TYPE_ERROR);
            $('#zj_serverTime').val('');
        }
    });

    initdata(false);

    //高级搜索
    $(".query-jiant").click(function () {
        var src = $("#jiant").attr("src");
        if (src.indexOf("jiant2") >= 0) {
            $("#jiant").attr("src", ctx + "/assets/img/jiant.png");
            $(".choose").show(300);
        } else {
            $("#jiant").attr("src", ctx + "/assets/img/jiant2.png");
            $(".choose").hide(300);
        }
    });
    //销单
    $(document).on("click", '.cancle', function () {
        $("#dialog_cancel_id").val($(this).attr('orderId'));
        $("#ok_modal_cancel").attr("disabled", false);
        $('#dialog_cancel').modal();
    });
    $("#close_modal_cancel").click(function () {
        $('#dialog_cancel').modal("hide");
    });
    $("#ok_modal_cancel").click(function () {
        if ($("input[name=cancel_reason]:checked").length == 0) {
            $.scojs_message("请选择销单原因", $.scojs_message.TYPE_ERROR);
            return false;
        }
        if ($("input[name=cancel_reason]:checked").val() == "other" && $("#dialog_cancel_content").val().length == 0) {
            $.scojs_message("请输入销单原因", $.scojs_message.TYPE_ERROR);
            return false;
        }
        var content = "";
        if ($("input[name=cancel_reason]:checked").val() == "other") {
            content = $("#dialog_cancel_content").val();
        } else {
            content = $("input[name=cancel_reason]:checked").val();
        }
        $(this).attr("disabled", true);
        $.post($(this).attr("action"), {'id': $("#dialog_cancel_id").val(), 'cause': content}, function (data) {
            if (data.success) {
                $.scojs_message("销单成功", $.scojs_message.TYPE_OK);
                setTimeout(function () {
                    window.location.reload(true);
                }, 1000);
            } else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
        }, 'json');
    });
    //备注		
    $(document).on("click", '.modifyCash', function () {
        var orderId = $(this).attr('orderId');
        var orderNo = $(this).attr('orderNo');
        var orderMemo = $(this).attr('orderMemo');
        $('#orderId').val(orderId);
        $('#orderNo').html(orderNo);
        $('#oldmemo').val(orderMemo);
        $('#dialog_modifyCash').modal();
    });
    $("#save").click(function () {
        $('#dialog_modifyCash').modal("hide");
        $.post(ctx + '/errand/remark', {'id': $('#orderId').val(), 'memo': $('#memo').val()}, function (data) {
            if (data.success) {
                $.scojs_message(data.message, $.scojs_message.TYPE_OK);
                setTimeout(function () {
                    window.location.reload(true);
                }, 1000);
            } else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                setTimeout(function () {
                    window.location.reload(true);
                }, 1000);
            }
        }, 'json');
    });
    $("#close_modal_memo").click(function () {
        $('#dialog_modifyCash').modal("hide");
    });
    //追加订单开始
    $(document).on("click", ".zhuijia", function () {
        var id = $(this).attr("orderId");
        window.open(ctx + "/errand/addmore/" + id, "_blank", "height=850,width=1220,scrollbars=yes,resizable=yes,alwaysRaised=yes,toolbar=no");
    });

    $("#zj_dialog_order").on("shown.bs.modal", function () {
        initialize2();
        var startPoint = new BMap.Point($("#zj_startLng").val(), $("#zj_startLat").val());
        var endPoint = new BMap.Point($("#zj_endLng").val(), $("#zj_endLat").val());
        zj_map.centerAndZoom(startPoint, 10);
        zj_driving.search(startPoint, endPoint);
    });
    $(document).on("click",".callback",function(){
    	$("#orderNo3").html($(this).attr("orderNo"));
    	$("#orderId3").val($(this).attr("orderId"));
    	$('#dialog_callback').modal();
    });
    $("#callback").click(function () {
        var cause = $("#cause3").val().trim();
        if (cause == null || cause == "") {
            $.scojs_message("收回原因不能为空", $.scojs_message.TYPE_ERROR);
            setTimeout(function () {
                window.location.reload(true);
            }, 1000);
            return;
        }
        var params = {id: $("#orderId3").val(), cause: $("#cause3").val()}
        $.post(ctx + '/errand/callback', params, function (object) {
            if (object.success) {
                $('#dialog_callback').modal("hide");
                $.scojs_message("收回成功", $.scojs_message.TYPE_OK);
                setTimeout(function () {
                    window.location.reload(true);
                }, 1000);
            } else {
                $.scojs_message("收回失败", $.scojs_message.TYPE_ERROR);
            }
        });
    });
    $("#close_modal_callback").click(function () {
        $('#dialog_callback').modal("hide");
    });
    //跑腿订单派单
    var startLng;
    var startLat;
    var clientName;
    var clientPhone;
    var fromPlace;
    $(document).on("click", ".errand_paidan", function () {
        startLng = $(this).attr("startLng");
        startLat = $(this).attr("startLat");
        clientName = $(this).attr("clientName");
        clientPhone = $(this).attr("clientPhone");
        fromPlace = $(this).attr("fromPlace");
        orderTypeId=$(this).attr("orderTypeId");
        $("#paidanOrderId").val($(this).attr("orderId"));
        $("#paidanClientName").html("");
        $("#paidanClientPhone").html("");
        $("#paidanFromPlace").html("");
        $("#dialog_paidan").modal();
        
    });

    $('#dialog_paidan').on('shown.bs.modal', function () {
        $("#paidanOrderLng").val(startLng);
        $("#paidanOrderLat").val(startLat);

        showClientMaker(startLng, startLat);
        getDrivers(startLng, startLat);

        $("#paidanClientName").html(clientName);
        $("#paidanClientPhone").html(clientPhone);
        $("#paidanFromPlace").html(fromPlace);
    });
    $('#distance').change(function () {
        showClientMaker($("#paidanOrderLng").val(), $("#paidanOrderLat").val());
        getDrivers($("#paidanOrderLng").val(), $("#paidanOrderLat").val());
    });
    $(document).on("click", ".paigeita", function () {
        var driverId = $(this).attr("data-id");
        if (window.confirm('确认要派单给该服务人员吗？')) {
            $.post(ctx + '/errand/paidan', {
                'driverId': driverId,
                'orderId': $("#paidanOrderId").val()
            }, function (data) {
                if (data.success) {
                    $.scojs_message("派单成功", $.scojs_message.TYPE_OK);
                    $("#dialog_paidan").modal("hide");
                    initdata(false);
                }
                else {
                    $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                }
            });
        }
    });

    //查询
    $("#searchButton").click(function () {
        if ($("input[name=treatment]").is(':checked')) {
            search_treatment = "true";
        } else {
            search_treatment = "false";
        }
        var DATE_FORMAT = /^[0-9]{4}-[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1} [0-2]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/;
        if ($("#startTime").val() != "") {
            if (!DATE_FORMAT.test($("#startTime").val())) {
                $.scojs_message("您输入的开始日期格式有误，正确格式如：2016-06-13 12:45", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if ($("#endTime").val() != "") {
            if (!DATE_FORMAT.test($("#endTime").val())) {
                $.scojs_message("您输入的结束日期格式有误，正确格式如：2016-06-13 12:45", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if ($("#startTime").val() != "" && $("#endTime").val() != "") {
            if ($("#startTime").val() > $("#endTime").val()) {
                $.scojs_message("启始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }
        if ($("#startFinishTime").val() != "") {
            if (!DATE_FORMAT.test($("#startFinishTime").val())) {
                $.scojs_message("您输入的日期格式有误，正确格式如：2016-06-13 12:45", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if ($("#endFinishTime").val() != "") {
            if (!DATE_FORMAT.test($("#endFinishTime").val())) {
                $.scojs_message("您输入的日期格式有误，正确格式如：2016-06-13 12:45", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if ($("#startFinishTime").val() != "" && $("#endFinishTime").val() != "") {
            if ($("#startFinishTime").val() > $("#endFinishTime").val()) {
                $.scojs_message("启始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        search_orderNumber = $("#orderNumber").val();
        search_clientPhone = $("#clientPhone").val();
        search_driverPhone = $("#driverPhone").val();
        search_companyName = $("#companyName").val();
        search_startTime = $("#startTime").val();
        search_endTime = $("#endTime").val();
        search_startFinishTime = $("#startFinishTime").val();
        search_endFinishTime = $("#endFinishTime").val();

        var orderTypeArr = [];
        $("input[name=orderType]:checked").each(function (index, element) {
            orderTypeArr.push($(element).val());
        });
        if (null != orderTypeArr && orderTypeArr.length > 0) {
            search_orderType = orderTypeArr.join(",");
        } else {
            search_orderType = [];
        }
        var errandOrderTypeArr = [];
        $("input[name=errandOrderType]:checked").each(function (index, element) {
            errandOrderTypeArr.push($(element).val());
        });
        if (null != errandOrderTypeArr && errandOrderTypeArr.length > 0) {
            errand_orderType = errandOrderTypeArr.join(",");
        } else {
            errand_orderType = [];
        }
        var statusArr = [];
        $("input[name=status]:checked").each(function (index, element) {
            statusArr.push($(element).val());
        });
        if (null != statusArr && statusArr.length > 0) {
            search_status = statusArr.join(",");
        } else {
            search_status = [];
        }
        offset = 0;
        initdata(false);
    });

    $(document).on("keydown", "body", function () {
        if (window.event.keyCode == 13) {
            $("#searchButton").click();
        }
    });

    //滚动
//	$(window).scroll(function () {
//        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
//        //$(window).height()获取当前窗体的高度
//        //$(document).height()获取当前文档的高度
//        var bot = 0; //bot是底部距离的高度
//        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
//        	if(pageLoading){
//        		pageLoading=false;
//        		offset+=limit;
//        		initdata(true);
//        	}
//        }
//    });
    $("#export_button").click(function () {

        window.location = ctx + "/errand/exportOrder?" + "&orderNumber=" + $("#orderNumber").val() +
            "&clientPhone=" + $("#clientPhone").val() + "&driverPhone=" + $("#driverPhone").val() +
            "&companyName=" + $("#companyName").val() + "&orderType=" + search_orderType + "&status=" + search_status +
            "&errandOrderType=" + errand_orderType + "&startTime=" + $("#startTime").val() + "&endTime=" + $("#endTime").val();
    });

});

function initdata(isappend) {
    $.ajax({
        url: ctx + '/errand/orderlistData',
        type: 'GET',
        async: false,
        dataType: 'json',
        data: {
            "orderNumber": search_orderNumber,
            "treatment": search_treatment,
            "clientPhone": search_clientPhone,
            "driverPhone": search_driverPhone,
            "companyName": search_companyName,
            "startTime": search_startTime,
            "endTime": search_endTime,
            "startFinishTime": search_startFinishTime,
            "endFinishTime": search_endFinishTime,
            "orderType": search_orderType,
            "errandOrderType": errand_orderType,
            "status": search_status,
            "pager.offset": offset,
            "limit": limit,
        },
        success: function (result) {
            var newcontent = '';
            var totalElements = result.totalElements;
            $("#NoData").text("");


            if (totalElements > 0) {
                $(result.content).each(function (index, data) {
                    var mainButton = "";
                    var selectButton = "";
                    var stauts = "";
                    
                    if (data.status == 0) {
                    	if(hasPermission_errandPaidan){
                    		mainButton =
                                "<a href='#' orderId='" + data.id + "' fromPlace='" + data.startAddress + "' startLat='" + data.startLat
                                + "' startLng='" + data.startLng + "' clientName='" + data.passengerName + "' clientPhone='" + data.passengerPhone
                                +"' orderTypeId='" + data.orderTypeId
                                + "' class='btn btn-primary btn-xs errand_paidan'>派单</a>";
                    		
                    		selectButton += "<li><a href='" + ctx + "/errand/detail/" + data.id + "' class='btn-link'>查看</a></li>";
                    	}
                    	else{
                    		mainButton = "<a href='" + ctx + "/errand/detail/" + data.id + "' class='btn btn-primary btn-xs'>查看</a>";
                    	}
                        
                        status = "<span class='btn btn-xindan btn-xs'>未派单</span>";
                        
                        if (hasPermission_powercancel) {
                            selectButton += "<li><a href='#' orderId='" + data.id + "' orderNo='" + data.orderNo + "' class='btn-link cancle'>销单</a></li>";
                        }
                        if (hasPermission_errandCreate){
                        	selectButton += "<li><a href='#' orderId='" + data.id + "' orderNo=" + data.orderNo + " class='btn-link zhuijia'>追加</a></li>";
                        }
                    } else if (data.status == 1) {
                        mainButton = "<a href='#'  orderId='" + data.id + "' orderNo='" + data.orderNo + "' class='btn btn-primary btn-xs callback'>收回</a>";
                        selectButton += "<li><a href='" + ctx + "/errand/detail/" + data.id + "' class='btn-link'>查看</a></li>";
                        status = "<span class='btn btn-warning btn-xs'>已派单</span>";
                        if (hasPermission_powercancel) {
                            selectButton += "<li><a href='#' orderId='" + data.id + "' orderNo=" + data.orderNo + " class='btn-link cancle'>销单</a></li>";
                        }
                        if (hasPermission_errandCreate){
                            selectButton += "<li><a href='#' orderId='" + data.id + "' orderNo=" + data.orderNo + " class='btn-link zhuijia'>追加</a></li>";
                        }
                    } else if (data.status == 2 || data.status == 3) {
                        mainButton = "<a href='" + ctx + "/errand/detail/" + data.id + "' class='btn btn-primary btn-xs'>查看</a>";
                        if (hasPermission_errandCreate){
                            selectButton += "<li><a href='#'  orderId=" + data.id + " orderNo=" + data.orderNo + "   class='btn-link zhuijia'>追加</a></li>";
                        }
                        selectButton += "<li><a href='#'  orderId=" + data.id + " orderNo=" + data.orderNo + " class='btn-link cancle'>销单</a></li>";
                        selectButton += "<li><a href='#'  orderId=" + data.id + " orderNo=" + data.orderNo + " class='btn-link callback'>收回</a></li>";
                        status = "<span class='btn btn-danger btn-xs'>已接单</span>";
                    } else if (data.status == 4) {
                    	if(hasPermission_errandCreate){
                            mainButton = "<a href='#' orderId='" + data.id + "' orderNo=" + data.orderNo + " class='btn btn-primary btn-xs zhuijia'>追加</a>";
                            selectButton += "<li><a href='" + ctx + "/errand/detail/" + data.id + "' class='btn-link'>查看</a></li>";
                    	}
                    	else{
                    		mainButton = "<a href='" + ctx + "/errand/detail/" + data.id + "' class='btn btn-primary btn-xs'>查看</a>";
                    	}
                        status = "<span class='btn btn-success btn-xs'>已完成</span>";
                    } else if (data.status == 5) {
                    	if(hasPermission_errandCreate){
                            mainButton = "<a href='#' orderId='" + data.id + "' orderNo=" + data.orderNo + " class='btn btn-primary btn-xs zhuijia'>追加</a>";
                            selectButton += "<li><a href='" + ctx + "/errand/detail/" + data.id + "' class='btn-link'>查看</a></li>";
                    	}
                    	else{
                    		mainButton = "<a href='" + ctx + "/errand/detail/" + data.id + "' class='btn btn-primary btn-xs'>查看</a>";
                    	}
                        status = "<span class='btn btn-default btn-xs'>已销单</span>";
                    }
                    selectButton += "<li><a href='#' orderId='" + data.id + "' orderNo='" + data.orderNo + "' orderMemo='" + data.orderMemo + "' class='btn-link modifyCash'>备注</a></li>";
                    var allButton = "<div class='btn-group'>" +
                        mainButton +
                        "<button type='button' class='btn " + "btn-primary" + " btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>" +
                        "<span class='caret'></span>" +
                        "<span class='sr-only'>Toggle Dropdown</span>" +
                        "</button>" +
                        "<ul class='dropdown-menu' role='menu'>" +
                        selectButton +
                        "</ul>" +
                        "</div>";
                    //所属公司
                    var companyNameTd = "";
                    if (mainCompany) {
                        companyNameTd = "<td>" + data.companyName + "</td>";
                    }
                    var memotr = data.content;
                    if (memotr.length > 10) {
                        memotr = memotr.substring(0, 10) + "...";
                    }
                    var startAddress = data.startAddress;
                    if (startAddress != null && startAddress.length > 10) {
                        startAddress = startAddress.substring(0, 10) + "...";
                    }
                    var endAddress = data.endAddress;
                    if (endAddress != null && endAddress.length > 10) {
                        endAddress = endAddress.substring(0, 10) + "...";
                    }
                    var couponSpan = "";
                    if (data.couponId != null) {
                        couponSpan = "<span class='label status-td' style='color:#D4DDF1;background-color:#0063C3;'>券</span>";
                    }
                    
                    var tiaojiaTd="";
            		if(tiaojia){
            			tiaojiaTd="<td>" +(data.justKilometres==null?"-，":+data.justKilometres+"公里，")+(data.justMoney==null?"-":+data.justMoney+"元")+"</td>";
            		}
            		
            		//结算方式
            		var realCashTD="<td>-</td>";
            		if(data.status==4 && null!=data.preAndAfterPayType){
            			realCashTD="<td>" + (data.realPay != null ? data.realPay : 0) + "元（"+data.preAndAfterPayType+"）</td>";
            		}

                    newcontent += "<tr class='grid-data tr-hui'  >" +
                        "<td>" + allButton + "</td>" +
                        "<td>" + status + "</td>" +
                        "<td><a href='" + ctx + "/errand/detail/" + data.id + "' class='btn-link'>***" + data.orderNo.substring(8, data.orderNo.length) + "</a>" + couponSpan + "</td>" +
                        "<td>" + data.orderType + "</td>" +
                        realCashTD+
                        "<td>" + (data.budgetPay != null ? data.budgetPay : 0) + "元</td>" +
                        tiaojiaTd+
                        "<td>" + data.created + "</td>" +
                        "<td>" + data.channelName + "</td>" +
                        "<td>" + data.passengerName + "</td>" +
                        "<td>" + data.passengerPhone + "</td>" +
                        "<td>" + new Date(data.startTime).Format("MM/dd hh:mm") + "</td>" +
                        "<td>" + (startAddress == null ? "-" : startAddress) + "</td>" +
                        "<td>" + (endAddress == null ? "-" : endAddress) + "</td>" +
                        "<td>" + (data.employName == null || data.employName == "" ? "-" : data.employName) + "</td>" +
                        "<td>" + (data.employPhone == null || data.employPhone == "" ? "-" : data.employPhone) + "</td>" +
                        companyNameTd +
                        "<td>" + (memotr == null || memotr == "" ? "-" : memotr) + "</td>" +
                        "<td>" + (data.runtime != null ? data.runtime : 0) + "分钟</td>" +
                        "<td>" + (data.mileage != null ? data.mileage : 0) + "公里</td>" +
                        "<td>" + (data.waitedTime != null ? data.waitedTime : 0) + "分钟</td>" +
                        "<td>" + (data.waitPrice != null ? data.waitPrice : 0) + "元</td>" +
                        "<td>" + data.cancelCause + "</td>" +
                        "<td>" + allButton + "</td>" +
                        "</tr>";
                });
            }
            else {
                $("#NoData").text("当前页面暂无记录 ");
            }


            if (!isappend) {
                $("#order_tbody .grid-data").remove();
            }


            $("#order_tbody").append(newcontent);
            $("#order_tbody .grid-data").each(function (index, element) {
                $(element).fadeIn(200 + (index * 35));
            });
            if (!hasShowPages) {
                if (!isappend) {
                    currentTotalElements = result.content.length;
                    pageLoading = true;
                } else {
                    if (currentTotalElements < totalElements) {
                        currentTotalElements += result.content.length;
                        pageLoading = true;
                    } else {
                        pageLoading = false;
                    }
                }
            }
            if (hasShowPages) {
                firstLoadPages = true;
                $(".pageshow li a").html("共" + totalElements + " 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    page: (offset / limit) + 1,
                    onSelect: function (page) {
                        limit = pagingLimit;
                        offset = (page - 1) * limit;
                        if (!firstLoadPages) {
                            initdata(false);
                        }
                        firstLoadPages = false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });
            } else {
                //滚动达到pagingLimit条开始显示分页
//        		if(currentTotalElements==pagingLimit){
                pageLoading = false;
                hasShowPages = true;
                $(".pageshow").show();
                $(".pagedata").show();
                $(".pageshow li a").html("共" + totalElements + " 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    onSelect: function (page) {
                        limit = pagingLimit;
                        offset = (page - 1) * limit;
                        if (!firstLoadPages) {
                            initdata(false);
                        }
                        firstLoadPages = false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });
//            	}
            }
        }
    });
}
function showClientMaker(lng, lat) {
    var point = new BMap.Point(lng, lat);
    map = new BMap.Map("allmap");
    map.centerAndZoom(point, 14);
    map.enableScrollWheelZoom();
    var marker = new BMap.Marker(point);  // 创建标注
    map.addOverlay(marker);

    map.addControl(new BMap.MapTypeControl({
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
    }));

    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角，仅包含平移和缩放按钮

    var ctrl = new BMapLib.TrafficControl({
        showPanel: false //是否显示路况提示面板
    });
    map.addControl(ctrl);
    ctrl.setAnchor(BMAP_ANCHOR_TOP_LEFT);
}
function getDrivers(lng, lat) {
    var distance = $("#distance").val();
    $.get(ctx + '/driver/errandListDrivers', {'lng': lng, 'lat': lat, 'distance': distance}, function (data) {
        if (data && data.length > 0) {
            $("#paidanDrivers").html('');
            var orderTypeIded;
            var detailedJobType;
            $(data).each(function (i, driver) {
            	
            	orderTypeIded = orderTypeId+"";
            	detailedJobType = "-"+driver.detailedJobType;
            	if(detailedJobType.indexOf(orderTypeIded)>0){
                var detailStatus = '';
                if (!driver.workCar) {
                    detailStatus = 'kongxian';
                } else {
                    detailStatus = 'workcar';
                }
                var htm = '<div id="driver_marker_' + driver.id + '" class="sj-mark driver_marker_class" style="position:absolute;z-index:9;">' +
                    '<div class="sj-mark-ma sjcolor-' + detailStatus + '"><span>' + driver.realname + '</span></div>' +
                    '<div class="sj-mark-rk rkcolor-' + detailStatus + '"></div>' +
                    '</div>';
                if (driver.workCar) {
                    htm = '<div id="driver_marker_' + driver.id + '" class="driver_workcar_marker_class" data-z-index="9998" style="position:absolute;z-index:9998;width:110px;">' +
                        '<div class="em-' + detailStatus + '-l"></div>' +
                        '<div class="em-' + detailStatus + '-con">' + driver.realname + '</div>' +
                        '<div class="em-' + detailStatus + '-r"></div>' +
                        '</div>';
                }
                var driverpoint = new BMap.Point(driver.longitude, driver.latitude);
                var drivermarker = new BMapLib.RichMarker(htm, driverpoint, {
                    "anchor": new BMap.Size(-62, -40),
                    "enableDragging": true
                });
                drivermarker.driverid = driver.id;
                drivermarker.driverstatus = driver.status;
                map.addOverlay(drivermarker);
                $("#paidanDrivers").append("<div class='modal-sj-bd' style='display:none;'><button type='button' class='paigeita' data-id='" + driver.id + "'>派给</button><span>" + driver.realname + "</span><span>" + driver.phone + "</span><span style='font-size:12px;'>" + driver.distanceStr + "</span></div>");
            	} });
            $(".paigeita").each(function (index, element) {
                $(element).parent().fadeIn((index + 1) * 300);
            });
        } else {
            $("#paidanDrivers").html(distance + "公里范围内暂无推荐服务人员，您可以扩大范围看看。");
        }
    });
}
function showLoading() {
    if ($('#loadblacklayer').length == 0) {
        var dw = $(".table").width();
        var dh = $(".table").height();
        var backlayer = "<div id='loadblacklayer'><div style='margin-top:" + (dh / 2) + "px;margin-left:" + (dw / 2) + "px;'><img src='" + ctx + "/assets/css/images/loading.gif' /></div></div>"
        $("#order_tbody").append(backlayer);
        $('#loadblacklayer').css({
            "z-index": "9",
            "background": "#000",
            "opacity": "0.5",
            "position": 'absolute',
            "top": 0,
            "width": dw,
            "height": dh
        });
    }
}
function hideLoading() {
    if ($('#loadblacklayer').length > 0) {
        $('#loadblacklayer').remove();
    }
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
